#! /usr/bin/env python2

# Author: Raymond Barrett
# Email: barretrj@tcd.ie

import socket
import pygame
import Image
import sys
from time import sleep


#image_res = (1040,680)
image_res = [1024,768]
#image_res = (1280,720)

#image_res = (1900,1080)
image_res2 = (512, 384)
#chunk_size = 8192
#chunk_size = 4096
chunk_size = 2048

# Functions ===================================================================
def string2Surface(data):
	# We turn the data we revieved into a PIL image
	image = Image.fromstring("RGB", image_res2, data)

	# Turn the PIL image into a pygame surface
	image = pygame.image.frombuffer(image.tostring(), image_res2, "RGB").convert()
	image = pygame.transform.scale(image, image_res)

	return image
#==============================================================================
def get_frame(address):
	not_connected = True
	# Create a socket connection for connecting to the server
	while not_connected:
		try:
			client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			client_socket.connect(address)
			not_connected = False
		except:
			# print "Waiting for connection"
			sleep(1)
	buff = client_socket.recv(chunk_size)
	# print buff	
	image_size, _, data = buff.partition('::')
	image_size = int(image_size)
	# Recieve data from the server
	while len(data)<image_size:
		data += client_socket.recv(chunk_size)
	assert len(data) == image_size, "Image size is incorrect. %d, %d" % (len(data), image_size)

	return data
#==============================================================================
def main(addr):
	# Start PyGame:
	pygame.init()
	# Create a PyGame screen, and set its size to 640x480L
	screen = pygame.display.set_mode(image_res)
	# Set the window caption:
	pygame.display.set_caption('The Fishbowl')
	# Create a PyGame clock which will be used to limit the fps
	clock = pygame.time.Clock()

	timer = 0
	previousImage = ""
	image = ""

	while 1:
		# Check if the exit button has been pressed:
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				sys.exit()							      
		
		# Timer to limit how many images requested from the server each second
		if timer < 1:
			image = get_frame(addr)
			# put more time on the clock
			timer = 5
		else:
			timer -= 1

		clock.tick()
		print clock.get_fps()
	
		screen.blit(string2Surface(image),(0,0))
		pygame.display.update()

if __name__ == "__main__":
	main((socket.gethostname(), 50000))
